<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<!-- <view class="back-icon" @click="goBack">
				<text class="iconfont">&#xe8b5;</text>
			</view> -->
			<view>
				<image class="back" src="/static/images/白色左箭头.png" mode="" @click="goBack"></image>
			</view>
			<text class="nav-title">选择车辆</text>
		</view>

		<!-- 车辆列表 -->
		<view class="car-list">
			<view class="car-item" v-for="(car, index) in cars" :key="index" @click="toggleSelect(index)">
				<view class="car-info">
					<image :src="car.carType?.img || '/static/user3/car2.jpg'" mode="aspectFill" class="car-image"></image>
					<view class="car-details">
						<view class="car-model">
							<text class="label">车型：</text>
							<text class="value">{{ car.carBrand?.name }} {{ car.carType?.name }}</text>
						</view>
						<view class="car-plate">
							<text class="label">车牌：</text>
							<text class="value">{{ car.carNum }}</text>
						</view>
					</view>
				</view>
				<!-- <image src="/static/xiche/组 5 拷贝@3x.png"></image> -->
				<image :src="car.isSelected ? '/static/home/wash/组 5 拷贝@3x.png' : '/static/home/wash/椭圆 4 拷贝 2@3x.png'"
					mode="aspectFit" class="select-icon"></image>
			</view>
		</view>

		<!-- 添加车辆按钮 -->
		<view class="add-car-btn" @click="confirmSelection">
			<text>选择车辆</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import { onLoad } from '@dcloudio/uni-app';

	const cars = ref([]);
	const userId = ref(null);
	const tempSelectedIndex = ref(-1);

	// 获取用户车辆列表
	const fetchUserCars = async (userId) => {
		try {
			const res = await uni.request({
				url: `http://localhost:9402/carinfo/user/${userId}`,
				method: 'GET',
				header: {
					'Authorization': uni.getStorageSync('Token')
				}
			});
			
			if (res.data.code === 200 && res.data.data) {
				// 获取当前选中的车辆
				const currentSelectedCar = uni.getStorageSync('selectedCar');
				
				cars.value = res.data.data.map((car, index) => ({
					...car,
					isSelected: currentSelectedCar ? car.id === currentSelectedCar.id : car.defaultCar === 1
				}));

				// 找到当前选中车辆的索引
				if (currentSelectedCar) {
					tempSelectedIndex.value = cars.value.findIndex(car => car.id === currentSelectedCar.id);
				} else {
					// 如果没有选中的车辆，找到默认车辆的索引
					tempSelectedIndex.value = cars.value.findIndex(car => car.defaultCar === 1);
					if (tempSelectedIndex.value === -1 && cars.value.length > 0) {
						tempSelectedIndex.value = 0;
					}
				}
			} else {
				uni.showToast({
					title: '获取车辆列表失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取车辆列表失败:', error);
			uni.showToast({
				title: '网络请求失败',
				icon: 'none'
			});
		}
	};

	onLoad((options) => {
		if (options.userId) {
			userId.value = options.userId;
			fetchUserCars(options.userId);
		} else {
			uni.showToast({
				title: '参数不完整',
				icon: 'none'
			});
			setTimeout(() => {
				goBack();
			}, 1500);
		}
	});

	const goBack = () => {
		uni.navigateBack();
	};

	const toggleSelect = (index) => {
		// 更新临时选中状态
		cars.value.forEach((car, i) => {
			car.isSelected = i === index;
		});
		tempSelectedIndex.value = index;
	};

	const confirmSelection = () => {
		if (tempSelectedIndex.value === -1) {
			uni.showToast({
				title: '请选择车辆',
				icon: 'none'
			});
			return;
		}

		// 将选中的车辆信息存储到本地
		const selectedCar = cars.value[tempSelectedIndex.value];
		uni.setStorageSync('selectedCar', {
			id: selectedCar.id,
			uid: selectedCar.uid,
			typeId: selectedCar.typeId,
			carNum: selectedCar.carNum,
			defaultCar: selectedCar.defaultCar,
			carUser: selectedCar.carUser,
			carType: selectedCar.carType,
			carBrand: selectedCar.carBrand
		});
		
		// 返回上一页
		uni.navigateBack();
	};

	const addCar = () => {
		uni.navigateTo({
			url: `/pages/addcar/addcar?userId=${userId.value}`
		});
	};
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background: #F8F8F8;
	}

	.back {
		position: absolute;
		left: 30rpx;
		top: 50rpx;
		width: 15px;
		height: 15px;
		z-index: 2;
	}

	.nav-bar {
		display: flex;
		/* align-items: center; */
		justify-content: center;
		height: 228rpx;
		padding: 0 30rpx;
		background: #4080FF;
		color: #fff;
	}

	.back-icon {
		font-size: 40rpx;
	}

	.nav-title {
		font-size: 34rpx;
		font-weight: 500;
		margin: 0 auto;
		height: 88rpx;
		margin-top: 40rpx;
	}

	.right-icons {
		display: flex;
		gap: 20rpx;
	}

	.icon {
		width: 48rpx;
		height: 48rpx;
	}

	.car-list {
		padding: 20rpx;
		margin-top: -140rpx;
	}

	.car-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #FFFFFF;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 20rpx;
	}

	.car-info {
		display: flex;
		align-items: center;
		gap: 30rpx;
	}

	.car-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
	}

	.car-details {
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}

	.car-model,
	.car-plate {
		display: flex;
		align-items: center;
	}

	.label {
		color: #333333;
		font-size: 28rpx;
	}

	.value {
		color: #333333;
		font-size: 28rpx;
		font-weight: 500;
	}

	.select-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.add-car-btn {
		position: fixed;
		bottom: 40rpx;
		left: 40rpx;
		right: 40rpx;
		height: 88rpx;
		background: #4080FF;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #FFFFFF;
		font-size: 32rpx;
	}

	.add-icon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 10rpx;
	}
</style>